package com.minglv.mini.tools;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.ruoyi.common.utils.StringUtils;

public class JWTUtils {

    public static Boolean verifyLogin(String token){
        try {
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(MiniProgramConstants.JWT_SECRET)).build();
            DecodedJWT verify = jwtVerifier.verify(token);
            boolean openid = StringUtils.isNotEmpty(verify.getClaims().get("openid").asString());
            return openid;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

    /**
     * 获得用户id
     * @param token
     * @return
     */
    public static Long getUserid(String token){
        Long id = null;
        if (verifyLogin(token)) {
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(MiniProgramConstants.JWT_SECRET)).build();
            DecodedJWT verify = jwtVerifier.verify(token);
            id = verify.getClaims().get("id").asLong();
        }
        return id;
    }

}
